#include <func.h>

#define MAXLINE 1024

int main(int argc, char* argv[])
{
    int wfd = open("fifo1", O_WRONLY);  /* 阻塞点 */
    if (wfd == -1) {
        perror("open()");
        exit(1);
    }

    int rfd = open("fifo2", O_RDONLY); /* 阻塞点 */
    if (rfd == -1) {
        perror("open()");
        exit(1);
    }
    // 全双工通信建立
    printf("Established\n");

    char recvline[MAXLINE];
    char sendline[MAXLINE];

    fd_set mainfds; // 局部变量
    FD_ZERO(&mainfds);  // 初始化
                        // 放置监听的文件描述符
    FD_SET(STDIN_FILENO, &mainfds); // 监听STDIN_FILENO
    int maxfd = STDIN_FILENO;
    FD_SET(rfd, &mainfds);          // 监听rfd
    if (rfd > maxfd) {
        maxfd = rfd;
    }

    for(;;) {
        fd_set readfds = mainfds;   // 结构体的复制
        struct timeval timeout = {5, 0};
        int events = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
        // 返回
        switch (events) {
        case -1:
            perror("select()");
            exit(1);
        case 0:
            printf("TIMEOUT\n");
            continue;
        default:
            printf("timeout: {%ld, %ld}\n", timeout.tv_sec, timeout.tv_usec);

            // 有 I/O 事件就绪
            // 遍历 readfds, 找到就绪的事件
            if (FD_ISSET(STDIN_FILENO, &readfds)) {
                if(fgets(sendline, MAXLINE, stdin)) {
                    write(wfd, sendline, strlen(sendline) + 1);  // +1 for '\0'
                }
            }
            if (FD_ISSET(rfd, &readfds)) {
                int n = read(rfd, recvline, MAXLINE);
                if (n < 0) {
                    perror("read()");
                    exit(1);
                } else if(n == 0) {
                    // 对方关闭管道
                    goto end;
                } else {
                    printf("From p1: %s", recvline);
                }
            }
            break;
        }
    }

end:
    close(rfd);
    close(wfd);
    return 0;
}

